<template>
  <div>
    <!-- 面包屑导航区域 -->

    <!-- 卡片视图区域 -->
    <el-card>
      <el-breadcrumb separator-class="el-icon-arrow-left" style="float:right">
        <el-breadcrumb-item :to="{ path: '/home' }">员工管理</el-breadcrumb-item>
        <el-breadcrumb-item>系统管理</el-breadcrumb-item>
      </el-breadcrumb>
      <!-- 搜索与添加区域 -->
      <el-row :gutter="26">
        <el-col :span="3">
          <el-input
            placeholder="请输入姓名"
            v-model="queryInfo.loginName"
            clearable
            @clear="getUserList"
          >
            <!-- <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button> -->
          </el-input>
        </el-col>
        <el-col :span="3">
          <el-input placeholder="请输入电话" v-model="queryInfo.mobile" clearable @clear="getUserList">
            <!-- <el-button type="primary" @click="getUserList">搜索</el-button> -->
          </el-input>
        </el-col>
        <el-col :span="2">
          <el-button type="primary" @click="getUserList">搜索</el-button>
        </el-col>
        <el-col :span="2">
          <el-button type="danger" @click="showAddDialog">添加用户</el-button>
        </el-col>
        <el-col :span="4">
          <BookTypeOption v-model="bookType" />
        </el-col>
        <el-col :span="2">
          <el-button
            type="success"
            @click="handleDownload"
            icon="el-icon-document"
            :loading="downloadLoading"
          >导出数据</el-button>
        </el-col>
        <!-- <el-col :span="2">
          
        </el-col>-->
      </el-row>

      <!-- 用户列表区域 -->
      <el-table
        :data="userlist"
        border
        stripe
        id="selectTable"
        v-loading="listLoading"
        element-loading-text="Loading..."
      >
        <el-table-column label="序号" type="index"></el-table-column>
        <el-table-column label="员工编号" prop="id"></el-table-column>

        <el-table-column label="登录名" prop="username"></el-table-column>
        <el-table-column label="姓名" prop="loginName"></el-table-column>
        <el-table-column label="性别">
          <template slot-scope="scope">
            <span v-if="scope.row.sex==0">男</span>
            <span v-else>女</span>
          </template>
        </el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <!-- <el-table-column label="角色" prop="role_name"></el-table-column> -->
        <!-- <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="userStateChanged(scope.row)"></el-switch>
          </template>
        </el-table-column>-->
        <el-table-column label="操作" width="240px">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button type="primary" size="mini" @click="showEditDialog(scope.row.id)">编辑</el-button>
            <!-- 删除按钮 -->
            <el-button type="danger" size="mini" @click="removeUserById(scope.row.id)">删除</el-button>
            <!-- 分配角色按钮 -->
            <!-- <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false"> -->
            <el-button type="success" size="mini" @click="setRole(scope.row)">分配角色</el-button>
            <!-- </el-tooltip> -->
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.currentPage"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>

    <!-- 添加用户的对话框 -->
    <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="25%" @close="addDialogClosed">
      <!-- 内容主体区域 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
        <!-- <el-form-item label="部门">
          <el-input @click.native="selectDept" v-model="userForm.deptName"></el-input>
        </el-form-item>-->
        <el-form-item label="姓名" prop="loginName">
          <el-input v-model="addForm.loginName"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <!-- <el-switch v-model="addForm.sex" @change="ad"></el-switch> -->
          <!-- <el-input v-model="addForm.sex"></el-input> -->
          <el-select v-model="addForm.sex" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
        <el-form-item label="登录名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password" type="password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户的对话框 -->
    <el-dialog title="修改用户" :visible.sync="editDialogVisible" width="50%" @close="editDialogClosed">
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px">
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色的对话框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="setRoleDialogVisible"
      width="25%"
      @close="setRoleDialogClosed"
    >
      <div>
        <p>当前的用户：{{userInfo.username}}</p>
        <p>当前的角色：{{userInfo.roleName==null?'未分配角色':userInfo.roleName}}</p>
        <p>
          分配新角色：
          <el-select v-model="selectedRoleId" placeholder="请选择">
            <el-option v-for="item in rolesList" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
// options components
// import FilenameOption from './components/FilenameOption'
// import AutoWidthOption from './components/AutoWidthOption'
import BookTypeOption from "./components/BookTypeOption";
import FileSaver from "file-saver";
import XLSX from "xlsx";
export default {
  name: "ExportExcel",
  components: {
    BookTypeOption,
    //  FilenameOption, AutoWidthOption
  },
  data() {
    // 验证邮箱的规则
    var checkEmail = (rule, value, cb) => {
      // 验证邮箱的正则表达式
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;

      if (regEmail.test(value)) {
        // 合法的邮箱
        return cb();
      }

      cb(new Error("请输入合法的邮箱"));
    };

    // 验证手机号的规则
    var checkMobile = (rule, value, cb) => {
      // 验证手机号的正则表达式
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;

      if (regMobile.test(value)) {
        return cb();
      }

      cb(new Error("请输入合法的手机号"));
    };

    return {
      options: [
        {
          value: 0,
          label: "男",
        },
        {
          value: 1,
          label: "女",
        },
      ],
      value: "",
      list: [],
      listLoading: true,
      downloadLoading: false,
      filename: "员工信息表",
      autoWidth: true,
      bookType: "xlsx",
      // 获取用户列表的参数对象
      queryInfo: {
        loginName: "",
        mobile: "",
        // query: "",
        // 当前的页数
        currentPage: 1,
        // 当前每页显示多少条数据
        pageSize: 5,
      },
      allInfo: {
        loginName: "",
        mobile: "",
        // query: "",
        // 当前的页数
        currentPage: 1,
        // 当前每页显示多少条数据
        pageSize: 100,
      },
      userlist: [],
      total: 0,
      // 控制添加用户对话框的显示与隐藏
      addDialogVisible: false,
      // 添加用户的表单数据
      addForm: {
        username: "",
        sex: 0,
        mobile: "",
        loginName: "",
        password: "",
        email: "",
        // deptId: "",
        // deptName: "",
      },
      // 添加表单的验证规则对象
      addFormRules: {
        loginName: [
          { required: true, message: "请输入姓名", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "用户名的长度在3~10个字符之间",
            trigger: "blur",
          },
        ],
        username: [
          { required: true, message: "请输入登录名", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "用户名的长度在3~10个字符之间",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 15,
            message: "密码的长度在6~15个字符之间",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
      },
      // 控制修改用户对话框的显示与隐藏
      editDialogVisible: false,
      // 查询到的用户信息对象
      editForm: {},
      // 修改表单的验证规则对象
      editFormRules: {
        email: [
          { required: true, message: "请输入用户邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入用户手机", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
      },
      // 控制分配角色对话框的显示与隐藏
      setRoleDialogVisible: false,
      // 需要被分配角色的用户信息
      userInfo: {},
      // 所有角色的数据列表
      rolesList: [
        {
          id: 1,
          name: "系统管理员",
          content: "拥有所有角色的功能",
        },
        {
          id: 2,
          name: "客服人员",
          content: "拥有客户服务中心权限",
        },
        {
          id: 3,
          name: "调度中心管理员",
          content: "拥有调度中心权限",
        },
        {
          id: 4,
          name: "中心库房管理员",
          content: "拥有库房权限",
        },
        {
          id: 5,
          name: "配送中心管理员",
          content: "拥有配送中心权限",
        },
        {
          id: 6,
          name: "配送员",
          content: "无权限",
        },
      ],
      // 已选中的角色Id值
      selectedRoleId: 1,
    };
  },
  created() {
    if (sessionStorage.getItem("currentPage")) {
      this.queryInfo.currentPage = parseInt(
        sessionStorage.getItem("currentPage")
      );
    }
    if (sessionStorage.getItem("pageSize")) {
      this.queryInfo.pageSize = parseInt(sessionStorage.getItem("pageSize"));
    }
    if (sessionStorage.getItem("loginName")) {
      const loginName = sessionStorage.getItem("loginName");

      this.queryInfo.loginName = loginName;
      // alert(this.queryInfo.loginName);
    }
    if (sessionStorage.getItem("mobile")) {
      const mobile = sessionStorage.getItem("mobile");

      this.queryInfo.mobile = mobile;
    }
    this.getUserList();
  },
  methods: {
    //分页显示列表
    async getUserList() {
      this.listLoading = true;
      const { data: res } = await this.$http.post(
        "/api/user/getUserList",
        this.queryInfo
      );
      console.log(res);
      sessionStorage.setItem("currentPage", this.queryInfo.currentPage);
      sessionStorage.setItem("pageSize", this.queryInfo.pageSize);
      sessionStorage.setItem("loginName", this.queryInfo.loginName);
      sessionStorage.setItem("mobile", this.queryInfo.mobile);

      if (res.code !== 200) {
        return this.$message.error(res.msg);
      }
      this.userlist = res.data;
      console.log(this.userlist);

      this.total = res.total;
      this.listLoading = false;
    },
    //获取全部数据
    async getAllList() {
      const { data: res } = await this.$http.post(
        "/api/user/getUserList",
        this.allInfo
      );

      if (res.code !== 200) {
        return this.$message.error(res.msg);
      }
      this.list = res.data;
    },
    // 监听 pagesize 改变的事件
    handleSizeChange(newSize) {
      // console.log(newSize)
      this.queryInfo.pageSize = newSize;
      this.getUserList();
    },
    // 监听 页码值 改变的事件
    handleCurrentChange(newPage) {
      console.log(newPage);
      this.queryInfo.currentPage = newPage;
      this.getUserList();
    },
    // 监听 switch 开关状态的改变
    async userStateChanged(userinfo) {
      console.log(userinfo);
      const { data: res } = await this.$http.put(
        `/api/user/users/${userinfo.id}/state/${userinfo.mg_state}`
      );
      if (res.meta.status !== 200) {
        userinfo.mg_state = !userinfo.mg_state;
        return this.$message.error("更新用户状态失败！");
      }
      this.$message.success("更新用户状态成功！");
    },
    // 监听添加用户对话框的关闭事件
    addDialogClosed() {
      this.$refs.addFormRef.resetFields();
      
    },
    // 展示编辑用户的对话框
    showAddDialog() {

      this.addForm = {
        username: "",
        sex: 0,
        mobile: "",
        loginName: "",
        password: "",
        email: "",
        // deptId: "",
        // deptName: "",
      };
      this.addDialogVisible = true;
    },
    // 点击按钮，添加新用户
    async addUser() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return;
        // 可以发起添加用户的网络请求
        const { data: res } = await this.$http.post(
          "/api/user/addUser",
          this.addForm
        );

        if (res.code !== 200) {
          this.$message.error(res.msg);
        } else {
          this.$message.success("添加用户成功！");
          // 隐藏添加用户的对话框
          this.addDialogVisible = false;
          // 重新获取用户列表数据
          this.getUserList();
        }
      });
    },
    // 展示编辑用户的对话框
    async showEditDialog(id) {
      // console.log(id)
      const { data: res } = await this.$http.get(
        "/api/user/getUserById?id=" + id
      );

      if (res.code !== 200) {
        return this.$message.error(res.msg);
      }

      this.editForm = res.data;
      this.editDialogVisible = true;
    },
    // 监听修改用户对话框的关闭事件
    editDialogClosed() {
      this.$refs.editFormRef.resetFields();
    },
    // 修改用户信息并提交
    editUserInfo() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return;
        // 发起修改用户信息的数据请求
        const { data: res } = await this.$http.post(
          "/api/user/updateSaveUser",
          this.editForm
          // {
          //   email: this.editForm.email,
          //   mobile: this.editForm.mobile,
          // }
        );

        if (res.code !== 200) {
          return this.$message.error(res.msg);
        }

        // 关闭对话框
        this.editDialogVisible = false;
        // 刷新数据列表
        this.getUserList();
        // 提示修改成功
        this.$message.success(res.msg);
      });
    },
    // 根据Id删除对应的用户信息
    async removeUserById(id) {
      // 弹框询问用户是否删除数据
      const confirmResult = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);

      // 如果用户确认删除，则返回值为字符串 confirm
      // 如果用户取消了删除，则返回值为字符串 cancel
      // console.log(confirmResult)
      if (confirmResult !== "confirm") {
        return this.$message.info("已取消删除");
      }

      const { data: res } = await this.$http.get(
        "/api/user/deleteUserById?id=" + id
      );

      if (res.code !== 200) {
        return this.$message.error(res.msg);
      }

      this.$message.success(res.msg);
      this.getUserList();
    },
    // 展示分配角色的对话框
    async setRole(userInfo) {
      this.setRoleDialogVisible = false;
      this.selectedRoleId = 1;
      this.userInfo = {};
      this.userInfo = userInfo;

      // // 在展示对话框之前，获取所有角色的列表
      // const { data: res } = await this.$http.get("/api/user/roles");
      // if (res.meta.status !== 200) {
      //   return this.$message.error("获取角色列表失败！");
      // }

      // this.rolesList = res.data;

      this.setRoleDialogVisible = true;
    },
    // 点击按钮，分配角色
    async saveRoleInfo() {
      if (!this.selectedRoleId) {
        return this.$message.error("请选择要分配的角色！");
      }
      if (this.userInfo.roleName == null) {
        const { data: res } = await this.$http.get(
          "/api/role/addRole?uid=" +
            this.userInfo.id +
            "&rid=" +
            this.selectedRoleId
        );
        if (res.code !== 200) {
          return this.$message.error(res.msg);
        } else {
          this.$message.success(res.msg);
          this.setRoleDialogVisible = false;

          this.getUserList();
        }
      } else {
        const { data: res } = await this.$http.get(
          "/api/role/updateRole?uid=" +
            this.userInfo.id +
            "&rid=" +
            this.selectedRoleId
        );
        if (res.code !== 200) {
          return this.$message.error(res.msg);
        } else {
          this.$message.success(res.msg);
          this.setRoleDialogVisible = false;

          this.getUserList();
        }
      }
    },
    // 监听分配角色对话框的关闭事件
    setRoleDialogClosed() {},

    //导出数据deMo
    exportExcel() {
      /* 从表生成工作簿对象 */
      var wb = XLSX.utils.table_to_book(document.querySelector("#selectTable"));
      // var wb=XLSX.utils.json_to_sheet(this.addFormRules);
      /* 获取二进制字符串作为输出 */
      var wbout = XLSX.write(wb, {
        bookType: "xlsx",
        bookSST: true,
        type: "array",
      });
      try {
        FileSaver.saveAs(
          //Blob 对象表示一个不可变、原始数据的类文件对象。
          //Blob 表示的不一定是JavaScript原生格式的数据。
          //File 接口基于Blob，继承了 blob 的功能并将其扩展使其支持用户系统上的文件。
          //返回一个新创建的 Blob 对象，其内容由参数中给定的数组串联组成。
          new Blob([wbout], { type: "application/octet-stream" }),
          //设置导出文件名称
          "员工信息表.xlsx"
        );
      } catch (e) {
        if (typeof console !== "undefined") console.log(e, wbout);
      }
      return wbout;
    },
    //导出数据
    async handleDownload() {
      this.downloadLoading = true;

      await this.getAllList();

      import("@/vendor/Export2Excel").then((excel) => {
        const tHeader = [
          "id",
          "username",
          "password",
          "mobile",
          "loginName",
          "email",
          "sex",
          "roleName",
          "updateTime",
          "createTime",
        ];
        const mapTitle = [
          "员工编号",
          "登录名",
          "密码",
          "电话",
          "姓名",
          "邮箱",
          "性别",
          "角色名称",
          "更新时间",
          "创建时间",
        ];
        // const filterVal = ['id', 'title', 'author', 'pageviews', 'display_time']
        const list = this.list;
        const data = this.formatJson(tHeader, list);
        excel.export_json_to_excel({
          header: mapTitle,
          data,
          filename: this.filename,
          autoWidth: this.autoWidth,
          bookType: this.bookType,
        });
        this.downloadLoading = false;
      });
    },
    //数据格式转换
    formatJson(filterVal, jsonData) {
      return jsonData.map((v) =>
        filterVal.map((j) => {
          // if (j === 'timestamp') {
          //   return parseTime(v[j])
          // } else {
          return v[j];
          // }
        })
      );
    },
  },
};
</script>

<style lang="less" scoped>
/* 全局样式表 */
html,
body,
#app {
  height: 100%;
  margin: 0;
  padding: 0;
  min-width: 1366px;
}

.el-breadcrumb {
  margin-bottom: 15px;
  margin-right: 15px;
  font-size: 15px;
}

.el-card {
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.15) !important;
}

.el-table {
  margin-top: 15px;
  font-size: 12px;
}

.el-pagination {
  margin-top: 15px;
}

.el-steps {
  margin: 15px 0;
}

.el-step__title {
  font-size: 13px;
}

.ql-editor {
  min-height: 300px;
}
</style>
